package com.ayf.payment.game.api.service.payment.wanw;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.service.payment.IPaymentService;
import com.ayf.payment.game.api.service.payment.util.PackageHtmlPayementFormUtil;
import com.ayf.payment.game.api.service.payment.wanw.util.WanWSignUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class WANWPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        BaseResData baseResData = orderCreate(traceId,order,paymentChannelDTO,redirectUrl,actualOrderAmt,merchantPaymentProductDTO.getBusinessCode());
        String orderCreateUrl = "";
        if (baseResData.isSuccess()) {
            orderCreateUrl = baseResData.getData();
            if (StringUtils.isEmpty(orderCreateUrl)){
                LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 玩玩下单失败 请求接口成功，接口返回报文 Data为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                throw new NullSetException(traceId + "下单失败，请稍后重试！");
            }
        }
        LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 玩玩下单 通道支付URL[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),orderCreateUrl);
        order.setRandomAmt(BigDecimal.ZERO);
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code", "002");
        map.put("htmlMsg",orderCreateUrl);
        return map;
    }


    private BaseResData orderCreate(String traceId,Order order,PaymentChannelDTO paymentChannelDTO,String redirectUrl,BigDecimal actualOrderAmt,String businessCode){
        String methodName = "玩玩下单";
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }

        if (!redirectUrl.endsWith("/")){
            redirectUrl=redirectUrl.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("pay");
        Map<String,String> reqParam = new LinkedHashMap<>();
        reqParam.put("pid",getPayCode(businessCode));
        reqParam.put("cid",parter);
        reqParam.put("orderid",order.getMerchantOrderNo());
        reqParam.put("money",String.valueOf(actualOrderAmt));// 单位：元，其中有些产品因特殊原因忽略小数部分
        String sign= WanWSignUtil.getSign(traceId,methodName,reqParam,KeyValue);
        reqParam.put("sign",sign);
        reqParam.put("notifyurl",returnUrl.concat("gameapip/v/wanw/pay/notify"));
        reqParam.put("returnurl",returnUrl.concat("gameapip/v/wanw/pay/returns"));
        reqParam.put("mark",redirectUrl);
//        reqParam.put("remark","");
//        reqParam.put("createip","");

        BaseResData baseResData = new BaseResData();
        baseResData.setSuccess(true);
        baseResData.setData(PackageHtmlPayementFormUtil.packageHtmlPayementForm(reqParam,AuthorizationURL));
        return baseResData;
    }


    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {

    }

    private String getPayCode(String code){
        if("ALIPAY".equals(code) || "ANTCREDITPAY".equals(code)){
            return "2001";
        } else if("WECHAT".equals(code)){
            return "1001";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

    private static void testOrderCreate(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        Order order = new Order();
        Date currentDate = DateUtils.getNowDate();
        String orderCreateStr = DateUtils.dateToString(currentDate, DateUtils.formatPattern_full_03);
        String orderNo = "M" + orderCreateStr + SnowFlakeUtils.getUniqueId();
        order.setMerchantOrderNo(orderNo);
        order.setCreateTime(currentDate);
        order.setAmount(BigDecimal.valueOf(1));
        order.setMerchantId(1000);
        String traceId = SnowFlakeUtils.getTraceId28();
        String redirectUrl = "http://uatxy.xyouplay.com";
        String bussinessCode = "WECHAT";
        WANWPaymentService xinYou2PaymentService = new WANWPaymentService();
        BaseResData baseResData = xinYou2PaymentService.orderCreate(traceId,order,paymentChannelDTO,redirectUrl,order.getAmount(),bussinessCode);
        System.out.println("玩玩下单返回报文:"+JSONObject.toJSONString(baseResData));
    }

    private static PaymentChannelDTO getTestPaymentChannelDTO(){
        PaymentChannelDTO paymentChannelDTO = new PaymentChannelDTO();
        paymentChannelDTO.setPaymentUrl("https://api.jfxjpay.cn");
        paymentChannelDTO.setReturnUrl("http://uatxy.xyouplay.com");
        paymentChannelDTO.setChannelKey("a7bff0d5f20d47edbbecf594a199bfd1");
        paymentChannelDTO.setAccountNumber("10172");// 商户ID
        return paymentChannelDTO;
    }

    public static void main(String[] args) {
        testOrderCreate();
    }

}
